package com.work.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.work.listener.ExcelListener;
import com.work.service.IStudentService;
import com.work.util.ResultUtil;
import com.work.vo.ExcelVo;
import com.sun.deploy.net.URLEncoder;
import com.work.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.*;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private IStudentService studentService;

    private static ExecutorService executorService = new ThreadPoolExecutor(10, 10,
            2000L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(10));

    /**
     * 下载 文件
     *
     * @return
     */
    @GetMapping("/download")
    public void downloadStudent(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("我是文件名", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        //忽略字段
        Set<String> excludeColumnFiledNames = new HashSet<String>();
        excludeColumnFiledNames.add("academyId");
        excludeColumnFiledNames.add("majorId");
        excludeColumnFiledNames.add("classId");
        List data = studentService.data();
        int size = data.size();
        CountDownLatch countDownLatch = new CountDownLatch((size / 500) + (size % 500 == 0 ? 0 : 1));
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ExcelVo.class).build();

        /**
         * TODO 此处使用线程 试图加快图片的写入 但是不起作用
         *      猜测  easyWrite的方法是异步执行，导致不等当前子线程执行结束便进行 -1 操作
         */

//        for (int i = 0; i < size; i += 500) {
//            List newData = data.subList(i, i + 500);
//            int j = i;
//            executorService.submit(() -> {
//
//                WriteSheet writeSheet = EasyExcel.writerSheet(j, "模板" + j).build();
//                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
//                excelWriter.write(newData, writeSheet);
//
//                countDownLatch.countDown();
//
//            });
//        }
//        try {
//            countDownLatch.await();
//            excelWriter.finish();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        EasyExcel.write(response.getOutputStream(), ExcelVo.class)
                .excludeColumnFiledNames(excludeColumnFiledNames)
                .sheet("模板")
                .doWrite(data); //用io流来写入数据
        excelWriter.finish();

    }

    //上传文件
    @PostMapping("/upload")
    @ResponseBody
    public ResultVo upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ExcelVo.class, new ExcelListener(studentService)).sheet().doRead();
        return ResultUtil.success();
    }


}
